// 获取URL中的GET参数
function getUrlParams() {
    let params = {};
    // 获取当前URL的查询字符串部分
    let queryString = window.location.search.substring(1);
    // 将查询字符串按&分割成数组
    let paramPairs = queryString.split('&');

    // 遍历参数对
    for (let i = 0; i < paramPairs.length; i++) {
        let pair = paramPairs[i].split('=');
        // 确保参数名和值都存在
        if (pair[0] && pair[1]) {
            // 解码参数值并存储到对象中
            params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
        }
    }

    return params;
}

// 获取指定参数名的值
function getUrlParam(name) {
    const params = getUrlParams();
    return params[name] || null; // 如果参数不存在返回null
}

function getFormattedDate() {
    var today = new Date();
    var year = today.getFullYear();
    var month = (today.getMonth() + 1).toString().padStart(2, '0'); // 月份需要加1，且保证两位数
    var day = today.getDate().toString().padStart(2, '0'); // 日期需要保证两位数
    return year + month + day;
}
// (parseFloat()*10).toFixed(0);

function getFormattedDateTime() {
    var today = new Date();
    var year = today.getFullYear();
    var month = (today.getMonth() + 1).toString().padStart(2, '0'); // 月份需要加1，且保证两位数
    var day = today.getDate().toString().padStart(2, '0'); // 日期需要保证两位数
    var hours = today.getHours().toString().padStart(2, '0'); // 小时需要保证两位数
    var minutes = today.getMinutes().toString().padStart(2, '0'); // 分钟需要保证两位数
    var seconds = today.getSeconds().toString().padStart(2, '0'); // 秒数需要保证两位数
    // return year + month + day + hours + minutes + seconds;
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
var now_date_str = getFormattedDate();


function getSelectedRadioButtonValue(groupName) {
    var options = document.getElementsByName(groupName);
    for (var i = 0; i < options.length; i++) {
        if (options[i].checked) {
            return options[i].value;
        }
    }
    return null; // 如果没有选中的单选按钮
}
function getRandomNumber() {
    return Math.floor(Math.random() * 90000) + 10000;
}


function msg(userIndex, content) {
    let user = findUser(userIndex);

    let msg = {
        msg_id: getTime(),
        uid: user.uid,
        sec_openid: user.uid, // 用户的加密sec_openid，当前其实没有加密
        type: "msg", // 消息类型：礼物
        content: content,
        avatar_url: user.head,
        nickname: user.name,
        timestamp: getTime(),
        msgType: '弹幕',
    }
    sendMessage(JSON.stringify(msg));
}
//  粉丝团消息类型：1-升级，2-加团
function tuan(userIndex, content, type, level) {
    let user = findUser(userIndex);
    let msg = {
        uid: user.uid,
        sec_openid: user.uid,
        level: user.level,
        payGrade: user.payGrade,
        name: user.name,
        sex: user.sex,
        avatar: user.head,
        msgId: getTime(),
        timestamp: getTime(),
        msgType: '粉丝团',
        content: "恭喜 HooYooGame 成为第2653名二娃成员（测试消息，真实的不是这样的）",
        type: 1
    }
    sendMessage(JSON.stringify(msg));
}


function jinfang(userIndex, content) {
    let user = findUser(userIndex);
    let msg = {
        uid: user.uid,
        sec_openid: user.uid,
        level: user.level,
        payGrade: user.payGrade,
        name: user.name,
        sex: user.sex,
        avatar: user.head,
        msgId: getTime(),
        timestamp: getTime(),
        msgType: '进房',
        memberCount: 180
    }
    sendMessage(JSON.stringify(msg));
}

function guanzhu(userIndex, content) {
    let user = findUser(userIndex);
    let msg = {
        uid: user.uid,
        sec_openid: user.uid,
        level: user.level,
        payGrade: user.payGrade,
        name: user.name,
        sex: user.sex,
        avatar: user.head,
        msgId: getTime(),
        timestamp: getTime(),
        msgType: '关注',
        followCount: 180
    }
    sendMessage(JSON.stringify(msg));
}

function fenxiang(userIndex, content) {
    let user = findUser(userIndex);
    let msg = {
        uid: user.uid,
        sec_openid: user.uid,
        level: user.level,
        payGrade: user.payGrade,
        name: user.name,
        sex: user.sex,
        avatar: user.head,
        msgId: getTime(),
        timestamp: getTime(),
        msgType: '分享',
        shareType: 1
    }
    sendMessage(JSON.stringify(msg));
}


function gif(userIndex, gifIndex, nub) {
    // console.log(userIndex)
    if (nub == 0) {
        layer.msg('请设置赠送的数量');
        return;
    }
    let user = findUser(userIndex);
    let gif = findGift(gifIndex)
    let msg = {
        type: "gift",
        msg_id: getTime(),  // string类型id
        uid: user.uid,//uid
        sec_openid: user.uid,    // 用户的加密sec_openid，当前其实没有加密
        gift_id: gif.加密后礼物id,  // 加密的礼物id
        sec_gift_id: gif.加密后礼物id,//加密的礼物id
        gift_num: nub,        // 送出的礼物数量
        gift_value: gif.单价,    // 礼物总价值，单位分
        avatar_url: user.head,     // 用户头像
        nickname: user.name,      // 用户昵称(不加密)
        timestamp: getTime(), // 礼物毫秒级时间戳
        msgType: '礼物'
    }
    console.log(msg)
    sendMessage(JSON.stringify(msg));
}

function like(userIndex, nub) {
    if (nub == 0) {
        layer.msg('请设置点赞的数量');
        return;
    }
    let user = findUser(userIndex);
    let msg = {
        uid: user.uid,//uid
        sec_openid: user.uid,
        level: user.level,
        payGrade: user.payGrade,
        name: user.name,
        sex: user.sex,
        avatar: user.head,
        msgId: getTime(),
        timestamp: getTime(),
        msgType: '点赞',
        count: nub
    }
    sendMessage(JSON.stringify(msg));
}

function findUser(index) {
    if (typeof index == "object") {
        return index
    }
    let user = data.user[index]
    return user
}

function findGift(index) {
    let gif = data.gif[index]
    return gif
}

function getTime() {
    return new Date().getTime();
}

function tosat(msg, type = 1, time = 1800) {
    var css = {}
    if (type == 3) {
        css = {//礼物
            background: "linear-gradient(to right, #FAD961, #F76B1C)"
        }
    } else if (type == 2) {//点赞
        css = {
            background: "linear-gradient(to right, #0093E9, #80D0C7)"
        }
    } else if (type == 1) {//消息
        css = {
            background: "linear-gradient(to right, #00b09b, #96c93d)",
        }
    } else if (type == -1) {//错误
        css = {
            background: "linear-gradient(to right, #FFE53B, #FF2525)",
        }
    } else if (type == 100) {//系统
        css = {
            background: "linear-gradient(to right, #08AEEA, #2AF598)",
        }
    } else if (type == 101) {//延迟
        css = {
            background: "linear-gradient(to right, #BBBBBB, #FFFFFF)",
        }
    }
    Toastify({
        text: msg,
        duration: time,
        style: css,
        gravity: "bottom", // `top` or `bottom`
    }).showToast();
}


function random(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function uid() {//随机玩家ID
    return random(0, 100);
}

function gid() {//随机礼物ID
    return random(0, 8);
}

// 房间号缓存功能
function saveRoomId(roomId) {
    localStorage.setItem('roomId', roomId);
}

function getRoomId() {
    return localStorage.getItem('roomId') || '';
}

// sendMessage接口函数
function sendMessage(jsonData) {
    const roomId = document.getElementById('roomId').value || getRoomId();

    if (!roomId) {
        tosat('请输入房间号', -1);
        return;
    }

    // 保存房间号到缓存
    saveRoomId(roomId);

    // 解析传入的JSON数据以确定消息类型
    let msgType = 'live_comment'; // 默认为评论
    try {
        let j = JSON.parse(jsonData);
        if (j.type === 'gift') {
            msgType = 'live_gift';
        }
        delete j.type;
        let data = [j];
        jsonData = JSON.stringify(data);

    } catch (e) {
        console.warn('解析JSON数据失败，使用默认消息类型');
    }

    // 发送HTTP请求
    fetch('/msg', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'x-msg-type': msgType,
            'x-roomid': roomId
        },
        body: jsonData
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络请求失败');
            }
            return response.text();
        })
        .then(data => {
            if (data === 'ok') {
                console.log('消息发送成功');
                tosat('消息发送成功', 100);
            } else {
                throw new Error('服务器响应异常');
            }
        })
        .catch(error => {
            console.error('消息发送失败:', error);
            tosat('消息发送失败: ' + error.message, -1);
        });
}
